package top.codedance.iotp.common.util;

import top.codedance.iotp.common.entity.URLEntity;

import java.net.URI;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class URLUtils {
    /**
     * 解析url，把url字符串拆分开三部分
     * @param url
     * @return
     */
    public static URLEntity parseURL(String url){
        URLEntity urlEntity = new URLEntity();
        try {
            URI u = new URI(url);
            urlEntity.setProtocol(u.getScheme());
            urlEntity.setUserinfo(u.getUserInfo());
            urlEntity.setHost(u.getHost());
            urlEntity.setPort(u.getPort());
            urlEntity.setUri(u.getPath());
            urlEntity.setQuery(u.getQuery());
            String query = u.getQuery();
            if(query != null) {
                urlEntity.setParams(parseQueryString(query));
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return urlEntity;
    }

    /**
     * 通过实体生成url字符串
     * @param urlEntity
     * @return
     */
    public static String genURL(URLEntity urlEntity){
        String url = "";
        try {
            URI u = new URI(urlEntity.getProtocol(), urlEntity.getUserinfo(), urlEntity.getHost(), urlEntity.getPort(), urlEntity.getUri(), urlEntity.getQuery(), null);
            url = u.toString();
        } catch (Exception e){
            e.printStackTrace();
        }
        return url;
    }

    /**
     * 解析查询字符串
     * @param queryString
     * @return
     */
    public static Map<String, String> parseQueryString(String queryString) {
        Map<String, String> paramMap = new HashMap<>();
        String[] params = queryString.split("&");
        for (String param : params) {
            try {
                String[] keyValue = param.split("=");
                String key = URLDecoder.decode(keyValue[0], "UTF-8");
                String value = URLDecoder.decode(keyValue[1], "UTF-8");
                paramMap.put(key, value);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        return paramMap;
    }
}
